package com.partner.frame.common;

import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.partner.frame.Result;

/**
 * 主要针对于controller 方法验证。
 * 使用方法： 参数中添加@Vaild注解与BindingResult。然后自动验证。
 * 如果验证失败：然后json字符串 {result:false,message:'java bean中验证message'}
 * User: dwr
 * Date: 17-2-23
 */
public class BindingResultAop {


    /**
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    	BindingResult bindingResult = null;
        Result rs = new Result();
        rs.setStatus(ConstantsMark.COMMON_ERROR);
		rs.setObject(ConstantsMark.COMMON_BLANK);
        for(Object arg:joinPoint.getArgs()){
            if(arg instanceof BindingResult){
                bindingResult = (BindingResult) arg;
            }
        }
        if(bindingResult != null){
            List<ObjectError> errors = bindingResult.getAllErrors();
            if(errors.size()>0){
                StringBuilder msg = new StringBuilder();
                for(ObjectError error :errors){
                    msg.append(error.getDefaultMessage());
                    rs.setDesc(msg.toString());
                    return rs ;
                }
                
            }
        }
        return joinPoint.proceed();
    }
}
